package cn.ysym.tcsy;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import org.json.JSONObject;

import cn.ysym.dao.SettingDao;
import cn.ysym.model.Setting;
import cn.ysym.util.HttpUtil;

public class LoginActivity extends AppCompatActivity {
    private EditText etAccount;
    private EditText etPasswd;
    private SettingDao settingDao;
    private UserLoginTask userLoginTask;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        settingDao = new SettingDao(this);

        HttpUtil.SERVICE_URL_BASE = settingDao.query("urlPath").getSettingValue();

        etAccount = findViewById(R.id.etAccount);
        Setting userName = settingDao.query("userName");
        etAccount.setText(userName.getSettingValue());

        etPasswd = findViewById(R.id.etPasswd);
        Setting userPass = settingDao.query("userPass");
        etPasswd.setText(userPass.getSettingValue());

        progressBar = findViewById(R.id.progressBar);

        Button bLogin = findViewById(R.id.bLogin);
        bLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        etPasswd.requestFocus();

        Button bSetting = findViewById(R.id.bSetting);
        bSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, SettingActivity.class));
            }
        });
    }

    private void attemptLogin() {
        if (userLoginTask != null) {
            return;
        }

        // Reset errors.
        etAccount.setError(null);
        etPasswd.setError(null);

        String account = etAccount.getText().toString();
        String password = etPasswd.getText().toString();
        progressBar.setVisibility(View.VISIBLE);
        userLoginTask = new UserLoginTask(account, password);
        userLoginTask.execute((Void) null);
    }

    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
        private String account;
        private String password;
        private String errMsg = "账号或密码错误";

        UserLoginTask(String account, String password) {
            this.account = account;
            this.password = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                req.put("account", account);
                req.put("passwd", password);
                String retStr = HttpUtil.postJson("login.sdo", req.toString());
                JSONObject retJson = new JSONObject(retStr);
                if (retJson.getInt("result") == 1) {
                    Setting userName = settingDao.query("userName");
                    userName.setSettingValue(account);
                    settingDao.update(userName);

                    Setting userPass = settingDao.query("userPass");
                    userPass.setSettingValue(password);
                    settingDao.update(userPass);

                    Setting sessionKey = settingDao.query("sessionKey");
                    sessionKey.setSettingValue(retJson.getString("sessionKey"));
                    settingDao.update(sessionKey);

                    Setting loginType = settingDao.query("loginType");
                    loginType.setSettingValue("1");
                    settingDao.update(loginType);

                    return true;
                } else errMsg = retJson.getString("message");
            } catch (Exception e) {
                errMsg = e.getMessage();
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            userLoginTask = null;
            progressBar.setVisibility(View.GONE);

            if (success) {
                finish();
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
            } else {
                etPasswd.setError(errMsg);
                etPasswd.requestFocus();
            }
        }
    }

}
